package comment

import (
	"community-service/cmd/api/internal/models/model"
	"community-service/cmd/api/internal/svc"
	"community-service/cmd/api/internal/types"
	e "community-service/pkg/errorx"
	"context"
	user "gitee.com/vzerx/proto-contracts/auth"
	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
)

type CreatePostCommentLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreatePostCommentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreatePostCommentLogic {
	return &CreatePostCommentLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreatePostCommentLogic) CreatePostComment(req *types.PostCommentCreateReq) (resp *types.Empty, err error) {

	// 检查帖子是否存在
	var existPost model.CsCommunityPost
	if err = l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityPost{}).
		Where("id = ?", req.Id).Find(&existPost).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if existPost.ID == 0 {
		return nil, e.NewGrpcErr(codes.NotFound, e.CommentPostNotFound)
	}

	// 获取当前用户信息
	userInfo, err := l.svcCtx.User.GetUserInfo(l.ctx, &user.UserInfoReq{
		UserId: req.UserId,
	})
	if err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if userInfo == nil || userInfo.UserId == 0 {
		return nil, e.NewGrpcErr(codes.NotFound, e.ErrorNotFound)
	}

	// 构建评论记录
	comment := &model.CsCommunityPostComment{
		PostID:         req.Id,
		Pid:            req.Pid,
		CreateUser:     req.UserId,
		CreateUsername: userInfo.UserName,
		Content:        req.Content,
		IsTopped:       false,
	}

	query := l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityPostComment{}).
		Select("post_id", "content", "is_topped", "create_user", "create_username")

	// 如果是回复评论，需要验证父评论是否存在，并获取被回复的用户信息
	if req.Pid > 0 {
		var parentComment model.CsCommunityPostComment
		if err = l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityPostComment{}).
			Where("id = ? AND post_id = ?", req.Pid, req.Id).Find(&parentComment).Error; err != nil {
			return nil, e.NewGrpcErr(codes.Internal, e.DBError)
		}

		if parentComment.ID == 0 {
			return nil, e.NewGrpcErr(codes.NotFound, e.CommentNotFound)
		}

		// 设置回复用户信息
		comment.ReplyUser = parentComment.CreateUser
		comment.ReplyUsername = parentComment.CreateUsername
		query.Select("pid", "post_id", "content", "is_topped", "create_user", "create_username", "reply_user", "reply_username")
	}

	// 创建评论
	if err = query.Create(comment).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	return &types.Empty{}, nil
}
